<template>
	<view
		class="myseeting-page"
		style="padding-top: 20px"
	>
		<!-- 导航栏 -->
		<view class="myseeting-nav-warp">
			<view class="myseeting-nav">
				<view class="back">
					<i
						class="certishare-icon"
						@click="back"
					>
						<span>&#xe602;</span>
					</i>
				</view>
				<view class="text">
					<span>编辑个人资料</span>
				</view>
				<view class="sub-button">
					<u-button
						type="primary"
						size="mini"
						@click="submitInfo"
					>
						提交
					</u-button>
				</view>
			</view>
		</view>

		<view class="seeting-header">
			<view class="header-bg">
				<image
					style="width: 100%; height: 100%; background-color: #eeeeee"
					:src="user.userInfo.profileBackground"
					@click="changeProfileBackground"
				></image>
			</view>
		</view>
		<view class="seeting-body-warp">
			<view class="seeting-body">
				<view class="user-icon">
					<image
						style="width: 100%; height: 100%; background-color: #eeeeee"
						:src="user.userInfo.avatar"
						@click="changeAvatar"
					></image>
				</view>
				<view class="informations-items">
					<u--form
						labelPosition="left"
						:model="user"
						:rules="rules"
						ref="uForm"
					>
						<!-- 姓名 -->
						<u-form-item
							label="姓名"
							prop="userInfo.username"
							borderBottom
							ref="item1"
						>
							<u--input
								v-model="user.userInfo.username"
								border="none"
							></u--input>
						</u-form-item>
						<!-- 性别 -->
						<u-form-item
							label="性别"
							borderBottom
							@click="
								showSex = true;
								hideKeyboard();
							"
							ref="item1"
						>
							<u--input
								v-model="user.userInfo.gender"
								disabled
								disabledColor="#ffffff"
								placeholder="请选择性别"
								border="none"
							></u--input>
							<u-icon
								slot="right"
								name="arrow-right"
							></u-icon>
						</u-form-item>
						<!-- 地址 -->
						<u-form-item
							label="地址"
							borderBottom
							ref="item1"
						>
							<view
								class="showCity"
								style="width: 100%; height: 100%"
								@click="cityShow = true"
							>
								{{ cityName }}
							</view>
							<u-icon
								slot="right"
								name="arrow-right"
								@click="cityShow = true"
							></u-icon>
						</u-form-item>
						<!-- 生日 -->
						<u-form-item
							label="生日"
							borderBottom
							ref="item1"
							@click="showBirthday = true"
						>
							<picker
								mode="date"
								:value="user.userInfo.birthday"
								:start="startDate"
								:end="endDate"
								@change="bindDateChange"
							>
								<view class="date-picker">{{ user.userInfo.birthday }}</view>
							</picker>

							<u-icon
								slot="right"
								name="arrow-right"
							></u-icon>
						</u-form-item>
						<!-- 个性签名 -->
						<u-form-item
							label="介绍"
							prop="userInfo.name"
							borderBottom
							ref="item1"
						>
							<u--textarea
								v-model="user.userInfo.personSignature"
								placeholder="请输入内容"
								count
								maxlength="120"
							></u--textarea>
						</u-form-item>
						<!--  -->
					</u--form>
					<!-- 选择性别拉框 -->
					<u-action-sheet
						:show="showSex"
						:actions="actions"
						title="请选择性别"
						@close="showSex = false"
						@select="sexSelect"
					></u-action-sheet>
					<!-- 选择地区 -->
					<u-picker
						:show="cityShow"
						ref="uPicker"
						:columns="cityList"
						@confirm="cityConfirm"
						@change="changeHandler"
						@cancel="cityShow = false"
					></u-picker>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import cityData from '@/utils/city.js';
import { updateUserInformation } from '@/common/api/user.js';
import { getUserInfo } from '../../common/api/find.js';
export default {
	data() {
		return {
			showSex: false,
			cityList: [],
			cityLevel1: [],
			cityLevel2: [],
			cityLevel3: [],
			cityShow: false,
			cityName: '',
			user: {
				userInfo: {
					username: '',
					gender: '',
					address: '',
					birthday: '请选择日期',
					personSignature: '',
					avatar: '',
					profileBackground: ''
				}
			},
			imagesTempURL: '',
			pickers: {},
			actions: [
				{
					name: '男'
				},
				{
					name: '女'
				}
			],
			rules: {
				'userInfo.username': {
					type: 'string',
					required: true,
					message: '请填写姓名',
					trigger: ['blur', 'change']
				}
			}
		};
	},
	computed: {
		...mapState({
			userInfo: (state) => state.user.userInfo
		}),
		startDate() {
			return this.getDate('start');
		},
		endDate() {
			return this.getDate('end');
		}
	},
	methods: {
		back() {
			uni.navigateBack();
		},
		init() {
			const that = this;
			const uid = this.userInfo.uid;
			const query = ['avatar', 'profileBackground', 'address', 'birthday', 'email', 'gender', 'username', 'personSignature'];
			getUserInfo(uid, query)
				.then((responseData) => {
					that.user.userInfo.avatar = responseData.avatar;
					that.user.userInfo.address = responseData.address;
					that.user.userInfo.username = responseData.username;
					that.user.userInfo.gender = responseData.gender;
					that.user.userInfo.birthday = responseData.birthday;
					that.user.userInfo.profileBackground = responseData.profileBackground;
					that.cityName = responseData.address;
				})
				.catch((error) => {
					console.error('获取用户信息失败,', error);
				});
			this.initCityData();
		},
		//选择性别
		sexSelect(e) {
			this.user.userInfo.gender = e.name;
			console.log(e);
			// this.$refs.uForm.validateField('userInfo.sex');
		},
		//选择日期
		bindDateChange(e) {
			this.user.userInfo.birthday = e.detail.value;
		},
		//上传头像
		changeAvatar() {
			const that = this;
			uni.chooseImage({
				count: 1,
				success(res) {
					// console.log(JSON.stringify(res.tempFilePaths));
					// that.user.userInfo.avatar = JSON.stringify(res.tempFilePaths);
					that.imagesTempURL = res.tempFilePaths[0];
					that.uploadFilePromise(that.imagesTempURL);
				}
			});
		},
		//上传头像咯咯
		async uploadFilePromise() {
			const that = this;
			uni.uploadFile({
				url: 'https://gos.upload.kvxin.top/upload',
				filePath: this.imagesTempURL,
				name: 'file',
				formData: {
					uid: this.userInfo.uid
				},
				success(res) {
					const data = JSON.parse(res.data);
					const fileURL = data.fileURL;
					that.user.userInfo.avatar = fileURL;
				}
			});
		},
		//上传背景图咯咯
		async uploadBackGroundFilePromise() {
			const that = this;
			uni.uploadFile({
				url: 'https://gos.upload.kvxin.top/upload',
				filePath: this.imagesTempURL,
				name: 'file',
				formData: {
					uid: this.userInfo.uid
				},
				success(res) {
					const data = JSON.parse(res.data);
					const fileURL = data.fileURL;
					that.user.userInfo.profileBackground = fileURL;
				}
			});
		},
		initCityData() {
			// 遍历城市js
			cityData.forEach((item1, index1) => {
				let temp2 = [];
				this.cityLevel1.push(item1.provinceName);
				let temp4 = [];
				let temp3 = [];
				// 遍历市
				item1.cities.forEach((item2, index2) => {
					temp2.push(item2.cityName);
					// 遍历区
					item2.counties.forEach((item3, index3) => {
						temp3.push(item3.countyName);
					});
					temp4[index2] = temp3;
					temp3 = [];
				});
				this.cityLevel3[index1] = temp4;
				this.cityLevel2[index1] = temp2;
			});
			// 选择器默认城市
			this.cityList.push(this.cityLevel1, this.cityLevel2[0], this.cityLevel3[0][0]);
		},
		// 选中时执行
		changeHandler(e) {
			const {
				columnIndex,
				index,
				indexs,
				value,
				values,
				// 微信小程序无法将picker实例传出来，只能通过ref操作
				picker = this.$refs.uPicker
			} = e;
			if (columnIndex === 0) {
				// 选择第一列数据时
				// 设置第二列关联数据
				picker.setColumnValues(1, this.cityLevel2[index]);
				// 设置第三列关联数据
				picker.setColumnValues(2, this.cityLevel3[index][columnIndex]);
			} else if (columnIndex === 1) {
				// 选择第二列数据时
				// 设置第三列关联数据
				picker.setColumnValues(2, this.cityLevel3[indexs[0]][index]);
			}
		},
		// 单击确认按钮时执行
		cityConfirm(e) {
			// 输出数组 [省, 市, 区]
			console.log(e.value);
			this.cityName = e.value.join('-');
			this.user.userInfo.address = this.cityName;
			// 隐藏城市选择器
			this.cityShow = false;
		},
		getDate(type) {
			const date = new Date();
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let day = date.getDate();

			if (type === 'start') {
				year = year - 60;
			} else if (type === 'end') {
				year = year + 2;
			}
			month = month > 9 ? month : '0' + month;
			day = day > 9 ? day : '0' + day;
			return `${year}-${month}-${day}`;
		},
		hideKeyboard() {
			console.log('hideKeyBoard');
		},
		changeProfileBackground() {
			const that = this;
			uni.chooseImage({
				count: 1,
				success(res) {
					that.imagesTempURL = res.tempFilePaths[0];
					that.uploadBackGroundFilePromise(that.imagesTempURL);
				}
			});
		},
		async updata() {
			const uid = this.userInfo.uid;
			//发送网络请求
			const data = updateUserInformation(uid, this.user.userInfo).then((res) => {
				uni.showToast({
					title: '更新成功',
					icon: 'none'
				});
				uni.navigateTo({
					url: '/pages/myCenter/myCenter'
				});
			});
		},
		async submitInfo() {
			console.log(this.user.userInfo.birthday);
			//判断日期格式是否正确
			const date = this.user.userInfo.birthday;
			if (this.$moment(date, 'YYYY-MM-DD', true).isValid()) {
				uni.showLoading({
					title: '正在更新中...'
				});
				await this.updata();
				uni.hideLoading();
			} else {
				uni.showToast({
					title: '生日格式错误',
					icon: 'none'
				});
				return;
			}
		}
	},
	mounted() {
		this.init();
		console.log(this.userInfo);
	}
};
</script>

<style lang="scss">
.myseeting-page {
	width: 750rpx;
	height: 100vh;
	position: relative;
	.myseeting-nav-warp {
		width: 100%;
		height: 50px;
		display: flex;
		justify-content: center;

		.myseeting-nav {
			width: 90%;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.back {
				i {
					font-size: 26px;
					font-weight: 700;
				}
			}

			.text {
				font-size: 14px;
				font-weight: 700;
			}
		}
	}

	.seeting-header {
		width: 100%;
		height: 250px;
		background-color: red;

		.header-bg {
			width: 100%;
			height: 100%;

			.seeting-background {
				width: 100%;
				height: 100%;
			}
		}
	}

	.seeting-body-warp {
		width: 100%;
		height: 500px;
		background-color: #fff;
		position: absolute;
		top: 32%;
		border-radius: 30px 30px 0 0;

		.seeting-body {
			width: 100%;
			height: 100%;
			position: relative;
			top: 0%;
			left: 0%;
			display: flex;
			justify-content: center;

			.user-icon {
				width: 80px;
				height: 80px;
				border-radius: 50%;
				border: 5px solid #fff;
				position: absolute;
				top: 0%;
				left: 50%;
				transform: translate(-50%, -50%);
				overflow: hidden;
			}

			.informations-items {
				width: 90%;
				height: 100%;
				padding-top: 50px;
				// background-color: red;
			}
		}
	}
}
</style>
